package com.ruoyi.business.service.impl;

import com.ruoyi.business.service.IProcessService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class ProcessServiceImpl implements IProcessService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Override
    public Deployment deploy(String filePath) throws FileNotFoundException {
        Deployment deployment = null;
        //bpmn或者zip
        if (filePath.endsWith("zip")) {
            ZipInputStream inputStream = new ZipInputStream(new FileInputStream(filePath));
            deployment = repositoryService.createDeployment()
                    .addZipInputStream(inputStream)
                    .deploy();
        } else {
            deployment = repositoryService.createDeployment()
                    .addInputStream(filePath,new FileInputStream(filePath))
                    .deploy();
        }
        return deployment;
    }

    @Override
    public ProcessDefinition getProcessDefinitionByDeploymentId(String deploymentId) {
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
    }

    @Override
    public InputStream getBpmnInputStream(String deploymentId) {
        //获取流程,获取到Bpmn的文件名
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //传入部署ID,Bpmn文件名,可以获取到bpmn输入流信息
        return repositoryService.getResourceAsStream(deploymentId,processDefinition.getResourceName());
    }

    @Override
    public InputStream getProcessImg(String deploymentId) {
        //获取流程定义ID
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //获取bpmnModel,主要描述节点,连线的信息
        BpmnModel bpmnModel=repositoryService.getBpmnModel(processDefinition.getId());
        //定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //第一个参数:bpmnModel 第二个参数: 需要高亮的节点集合 第三个参数:需要高亮连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public ProcessInstance startProcessInstance(String definitionKey, String businessKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(definitionKey,businessKey,variables);
    }

    @Override
    public Task getTaskByProcessInstanceId(String processInstanceId) {
        return taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public void addCandidateUser(Task task, Long userId) {
        taskService.addCandidateUser(task.getId(),String.valueOf(userId));
    }

    @Override
    public InputStream getProcessImgByInstanceId(String instanceId) {
        //获取流程定义ID
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        //获取bpmnModel,主要描述节点,连线的信息
        BpmnModel bpmnModel=repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        //定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //获取目前正在流转节点
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstance.getId());
        //第一个参数:bpmnModel 第二个参数: 需要高亮的节点集合 第三个参数:需要高亮连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, activeActivityIds, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void deleteProcessInstance(String instanceId) {
        runtimeService.deleteProcessInstance(instanceId,"撤销申请");
    }

    @Override
    public Long getTodoTsaskCount(String definitionKey, String userId) {
        return taskService.createTaskQuery().processDefinitionKey(definitionKey).taskCandidateUser(userId).count();
    }

    @Override
    public List<Task> selectTodoTaskList(String definitionKey, String userId, Integer starNum, Integer pageSize) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(userId)
                .orderByTaskCreateTime()
                .asc()
                .listPage(starNum,pageSize);
    }

    @Override
    public ProcessInstance getProcessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public Task getTaskByTaskId(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public void claimAndComplete(Task task, String userId, Boolean auditStatus, String comment) {
        String commentStr = auditStatus?"【同意】":"【拒绝】";
        commentStr +=comment;
        //1
        taskService.addComment(task.getId(),task.getProcessInstanceId(),commentStr);
        //2
        taskService.claim(task.getId(),userId);
        //3
        Map<String,Object>variables = new HashMap<>();
        variables.put(task.getTaskDefinitionKey(),auditStatus);
        taskService.complete(task.getId(),variables);


    }
}
